package com.zis.security.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zis.security.client.UserClient;
import com.zis.security.jwt.Audience;
import com.zis.security.jwt.JwtHelper;
import com.zis.security.model.AccessToken;
import com.zis.security.model.LoginPara;
import com.zis.security.service.ILoginService;
import com.zis.starter.core.ResponseEntity;
import com.zis.starter.redis.RedisUtil;
import com.zis.starter.utils.MD5Util;
import com.zis.starter.utils.RandomUtil;
import com.zis.starter.utils.SecurityUtil;
import com.zis.system.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create by wangshen 2018/2/6
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private Audience audience;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户登录
     * @param loginPara
     * @return
     */
    @Override
    public ResponseEntity userLogin(LoginPara loginPara) throws Exception {
        if (loginPara.getClientId() == null || loginPara.getClientId().equals("")) {
            return ResponseEntity.failure("未获取到客户端标识");
        }
        if (loginPara.getUserName() == null || loginPara.getUserName().equals("")) {
            return ResponseEntity.failure("请输入用户名");
        }
        if (loginPara.getPassword() == null || loginPara.getPassword().equals("")) {
            return ResponseEntity.failure("请输入密码");
        }
        // 验证用户名与密码的真实性
        ResponseEntity resp = userClient.findByLoginName(loginPara.getUserName());
        if (resp.getCode() != 0) {
            return ResponseEntity.failure("用户名不存在");
        }
        User user = JSON.parseObject(JSON.toJSONString(resp.getRespData()), User.class);
        //判断用户状态
        if (user.getIsEnabled() == 0) {
            return ResponseEntity.failure("当前用户已被禁用");
        }
        if (user.getIsLocked() == 0) {
            return ResponseEntity.failure("当前用户已经被锁定");
        }
        //======用户名存在，验证码密码======//
        //解密数据库密码
        String password = SecurityUtil.AESDncode(user.getSalt(), user.getPassword());
        String md5 = MD5Util.string2MD5(password+loginPara.getClientId());
        if (!md5.equals(loginPara.getPassword())) {
            return ResponseEntity.failure("密码错误");
        }
        // 生成accessToken
        String jwtToken = JwtHelper.createJWT(user.getUserId(), loginPara.getClientId() ,
                audience.getExpiresSecond() * 1000, audience.getBase64Secret());
        String[] tokenArr = jwtToken.split("\\.");
        AccessToken token = new AccessToken();
        token.setToken_prefix(tokenArr[0]);
        token.setToken(tokenArr[1]);
        token.setToken_suffix(tokenArr[2]);
        token.setToken_type("manager");
        token.setExpires_in(audience.getExpiresSecond());
        token.setAuthCode(user.getTails().get("authWord").toString());
        // 写入redis中
        redisUtil.set("system:login:"+tokenArr[1], token, token.getExpires_in());
        return ResponseEntity.success(JSON.parseObject(JSON.toJSONString(token)));
    }

    /**
     * 修改密码
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public ResponseEntity updatePassword(JSONObject params) throws Exception {
        String userId = params.containsKey("userId") ? params.getString("userId") : "";
        if (userId.equals("")) {
            return ResponseEntity.failure("未获取到用户信息");
        }
        String oldPwd = params.containsKey("oldPwd") ? params.getString("oldPwd") : "";
        if (oldPwd.equals("")) {
            return ResponseEntity.failure("请输入旧密码");
        }
        String newPwd = params.containsKey("newPwd") ? params.getString("newPwd") : "";
        if (newPwd.equals("")) {
            return ResponseEntity.failure("请输入旧密码");
        }
        String checkNewPwd = params.containsKey("checkNewPwd") ? params.getString("checkNewPwd") : "";
        if (checkNewPwd.equals("")) {
            return ResponseEntity.failure("请输入旧密码");
        }
        ResponseEntity userResp = userClient.selectById(userId);
        if (userResp.getCode() != 0) {
            return ResponseEntity.failure("未获取到用户信息");
        }
        User user = JSON.parseObject(JSON.toJSONString(userResp.getRespData()), User.class);
        String password = SecurityUtil.AESDncode(user.getSalt(), user.getPassword());
        if (!password.equals(oldPwd)) {
            return ResponseEntity.failure("旧密码不正确");
        }
        if (!newPwd.equals(checkNewPwd)) {
            return ResponseEntity.failure("两次输入的新密码不一致");
        }
        // 创建新的密码与校验码
        String slat = RandomUtil.getRandomStr(16);//16位密码校验码
        String newPassword = SecurityUtil.AESEncode(slat, newPwd);//密码加密
        User userParams = new User();
        userParams.setUserId(userId);
        userParams.setSalt(slat);
        userParams.setPassword(newPassword);
        userClient.update(userParams);
        return ResponseEntity.success("密码修改成功");
    }
}
